# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jaewon

import datetime
import re


def dump_csv_from_log(filepath,
                      begin_time=None,
                      end_time=None,
                      passive_base_pos=1.5,
                      agg_base_pos=2.0137):
  begin_time = begin_time or datetime.datetime.min
  end_time = end_time or datetime.datetime.max

  last_time = None
  last_sell_p = None
  last_buy_p = None
  last_ask0 = None
  last_bid0 = None
  last_mid_p = None
  last_balance = {'BNB': None, 'BTC': None, 'USDT': None}
  last_pos = None
  last_sum = None
  last_imbalance = None

  bnb_price = 9.0
  first_balance = None
  pnl = 0

  price_str_finder = re.compile('([0-9]+(\.[0-9]*){0,1}) @ ([0-9]+(\.[0-9]*){0,1})'
                                ' \(((-){0,1}[0-9]+(\.[0-9]*){0,1})\)')

  with open(filepath, 'r') as f:
    print('lineno,time,mid_price,pos,sum,imbalance,pnl')

    for lineno, line in enumerate(f.readlines()):
      dump = False

      last_time_str = line[9:32]
      if last_time_str[:5] == '2018-':
        last_time = datetime.datetime.strptime(last_time_str, '%Y-%m-%d %H:%M:%S,%f')

      if last_time is None or last_time < begin_time:
        continue

      if last_time >= end_time:
        break

      if line.startswith('*'):
        tokens = [t for t in line.strip().split(' ') if t]
        currency = tokens[1]
        if currency in last_balance.keys():
          agg_balance = float(tokens[3])
          pas_balance = float(tokens[4])
          last_balance[currency] = (agg_balance, pas_balance)

          if currency == 'USDT':
            if first_balance is None:
              first_balance = dict(last_balance)
              pnl = 0

            if last_mid_p:
              last_pos = last_balance['BTC'][1] - (passive_base_pos)
              last_sum = last_balance['BTC'][0] - (agg_base_pos) + last_pos
              pnl = ((sum(last_balance['BTC']) - sum(first_balance['BTC'])) * last_mid_p +
                     (sum(last_balance['USDT']) - sum(first_balance['USDT'])))

      elif line.startswith('-'):
        pass

      elif line.find('SoftArbStrategy] [2] SELL') != -1:
        m = price_str_finder.findall(line)
        last_sell_p = float(m[0][2])
        last_ask0 = last_sell_p - float(m[0][4])
        last_buy_p = float(m[1][2])
        last_bid0 = last_buy_p + float(m[1][4])
        last_mid_p = (last_ask0 + last_bid0) / 2.
        assert last_ask0 > last_bid0

      elif line.find('SoftArbStrategy] Imbalance') != -1:
        m = re.search('([0-9]+(\.[0-9]*){0,1}) USD', line)
        last_imbalance = float(m.group(1))
        dump = True

      if dump and last_time and last_mid_p and last_pos and pnl:
        print('%d,"%s",%.2f,%.1f,%.1f,%.1f,%.1f' %
              (lineno + 1, last_time, last_mid_p, last_pos, last_sum, last_imbalance, pnl))


dump_csv_from_log('/home/ec2-user/dev/coin/log_bitmex_bitfinex_soft_arb',
                  begin_time=datetime.datetime(2018, 2, 25, 0, 0, 0),
                  end_time=datetime.datetime(2018, 2, 26, 15, 0, 0))
